#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import signal
import time
import subprocess
import psutil
from .log import logger


def is_process_alive(pid):
    """Check if the process is alive"""
    if psutil.pid_exists(pid):
        return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
    return False


def signal_pid(pid, sig):
    try:
        os.kill(pid, sig)
    except OSError:
        pass

    for i in range(5):
        if not is_process_alive(pid):
            return True
        time.sleep(1)
    return False


def kill_process_tree(pid, sig=signal.SIGKILL, showinfo=False):
    children = subprocess.Popen(
        ["ps", "--ppid={}".format(pid), "-o", "pid="],
        stdout=subprocess.PIPE
    ).communicate()[0].split()
    if not signal_pid(pid, sig):
        return
    if showinfo:
        logger.info("killed process id: {}".format(pid))
    for child in children:
        if showinfo:
            logger.info("killing process id ...: {}".format(child))
        kill_process_tree(int(child), sig)


def get_children_processes(pid):
    cmd = "ps --ppid={} -o pid=".format(pid)
    children = subprocess.Popen(
        cmd.split(),
        stdout=subprocess.PIPE).communicate()[0].split()
    return [int(child) for child in children]

